using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;

namespace AssemblyVersionPortableArea.Areas.AssemblyVersion.Controllers
{
	public class AssemblyVersionController : Controller
	{
		public ActionResult Index()
		{
			return View((object) GetApplicationVersion());
		}

		public ActionResult ReleaseNotes()
		{
			return View("", "Site", GetReleaseNotes());
		}

		private string[] GetReleaseNotes()
		{
			Assembly assembly = GetAssembly();
			string[] names = assembly.GetManifestResourceNames();
			if (names.Any(name => IsReleaseNote(name)))
			{
				using (var stream = new StreamReader(assembly.GetManifestResourceStream(names.First(s => IsReleaseNote(s)))))
				{
					return stream.ReadToEnd().Split('\r');
				}
			}
			return new string[0];
		}

		private bool IsReleaseNote(string name)
		{
			return name.EndsWith("releasenotes.txt", true, null);
		}

		public ActionResult List()
		{
			return View("", "Site", GetReferencedAssemblies());
		}

		private AssemblyName[] GetReferencedAssemblies()
		{
			return GetAssembly().GetReferencedAssemblies().OrderBy(name => name.Name).ToArray();
		}

		private Assembly GetAssembly()
		{
			return System.Web.HttpContext.Current.ApplicationInstance.GetType().BaseType.Assembly;
		}

		private string GetApplicationVersion()
		{
			Assembly executingAssembly = GetAssembly();
			return executingAssembly.GetName().Version.ToString();
		}
	}
}